import {fetchList, add, edit, del} from '@/services/cms/CmsPageInfo';
import {arr2tree} from '@/utils/utils';
import {message} from 'antd';

export default {
  namespace: 'PCmsPageLeft',

  state: {
    list: [],
    tree: [],
  },

  effects: {
    * fetchList({payload, callback}, {call, put}) {
      const response = yield call(fetchList, payload);
      if (response.code === 0) {
        yield put({
          type: 'chgTree',
          payload: arr2tree(response.data),
        });
        yield put({
          type: 'chgList',
          payload: response.data,
        });
        callback && callback(response.data);
      }
    },

    * add({payload, callback}, {call}) {
      const response = yield call(add, payload);
      if (response.code === 0) {
        message.success('添加成功').then();
        callback && callback();
      }
    },

    * edit({payload, callback}, {call}) {
      const response = yield call(edit, payload);
      if (response.code === 0) {
        message.success('修改成功').then();
        callback && callback();
      }
    },

    * del({payload, callback}, {call}) {
      const response = yield call(del, payload);
      if (response.code === 0) {
        message.success('删除成功').then();
        callback && callback();
      }
    },

  },

  reducers: {
    chgList(state, action) {
      return {
        ...state,
        list: action.payload,
      };
    },
    chgTree(state, action) {
      return {
        ...state,
        tree: action.payload,
      };
    },
  },
};
